<!-- 添加商品 -->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="商品增加页"
    width="80%"
    :before-close="handleClose"
    @open="loadData"
  >
    <el-form :model="goodForm" ref="formRef" :rules="rules" label-width="0">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item prop="name" class="label-top">
            <el-input
              v-model="goodForm.name"
              placeholder="请输入商品名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item prop="price" class="label-top">
            <el-input-number
              v-model="goodForm.price"
              :precision="2"
              placeholder="请输入商品价格"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item prop="description" class="label-top">
            <el-input
              v-model="goodForm.description"
              placeholder="请输入商品描述"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item prop="image" class="label-top">
            <el-upload
              class="avatar-uploader"
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleAvatarChange"
            >
              <img
                v-if="imageUrl"
                :src="imageUrl"
                class="avatar"
                style="width: 100px; height: 100px; object-fit: cover"
              />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item prop="typeId" class="label-top">
            <el-select v-model="goodForm.typeId" placeholder="请选择商品类型">
              <el-option
                v-for="option in typeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="3">
          <el-form-item prop="isDelete" class="label-top">
            <el-select v-model="goodForm.isDelete" placeholder="请选择是否售卖">
              <el-option label="售卖" value="0"></el-option>
              <el-option label="不售卖" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确认添加</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-input-number {
  width: 100%;
}

.el-select {
  width: 100%;
}

:deep(.label-top) {
  .el-form-item__label {
    float: none;
    display: block;
    text-align: left;
    padding: 0 0 8px;
  }
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  display: block;
  width: 100px;
  height: 100px;
}
</style>

<script setup>
import {
  ref,
  reactive,
  defineEmits,
  onMounted,
  computed,
  defineExpose,
} from "vue";
import axios from "axios"; // 确保已导入 axios
import { ElMessage } from "element-plus"; // 用于显示提示信息

const emits = defineEmits(["update:modelValue", "refresh-list"]);
const dialogVisible = ref(false);

// 修改表单数据结构，与后端 Products 实体对应
const goodForm = reactive({
  name: "",
  price: "",
  description: "",
  image: "",
  typeId: "",
  isDelete: "0",
});

const handleClose = () => {
  dialogVisible.value = false;
  // 重置表单和图片预览
  Object.assign(goodForm, {
    name: "",
    price: "",
    description: "",
    image: "",
    typeId: "",
    isDelete: "0",
    imageFile: null,
  });
  imageUrl.value = "";
  emits("update:modelValue", false);
};

// 添加表单校验规则
const rules = {
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  price: [
    { required: true, message: "请输入商品价格", trigger: "blur" },
    { type: "number", message: "价格必须为数字", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error("价格必须大于0"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  description: [{ required: true, message: "请输入商品描述", trigger: "blur" }],
  typeId: [{ required: true, message: "请选择商品类型", trigger: "change" }],
};

// 获取表单引用
const formRef = ref(null);

// 修改图片处理相关函数
const handleAvatarChange = (file) => {
  if (beforeAvatarUpload(file.raw)) {
    goodForm.imageFile = file.raw;
    // 创建本地预览URL
    imageUrl.value = URL.createObjectURL(file.raw);
  }
};

// 修改提交表单函数
const submitForm = async () => {
  if (!formRef.value) return;

  // 手动验证图片是否已上传
  if (!goodForm.imageFile) {
    ElMessage.error("请上传商品图片");
    return;
  }

  try {
    await formRef.value.validate();

    // 第一步：提交商品基本信息
    const response = await axios.post(
      "/addGood",
      {
        name: goodForm.name,
        price: goodForm.price,
        description: goodForm.description,
        typeId: goodForm.typeId,
        isDelete: goodForm.isDelete,
        image: goodForm.image,
      },
      {
        headers: {
          Authorization: sessionStorage.getItem("Authorization"),
        },
      }
    );

    if (response.data.status === 200) {
      const productId = response.data.data; // 获取新增商品的ID

      // 第二步：上传图片
      const formData = new FormData();
      formData.append("file", goodForm.imageFile);

      try {
        const uploadResponse = await axios.post(
          `/uploadFiles/${productId}`,
          formData,
          {
            headers: {
              Authorization: sessionStorage.getItem("Authorization"),
              "Content-Type": "multipart/form-data",
            },
          }
        );

        if (uploadResponse.data.status === 200) {
          ElMessage.success("商品添加成功");
          handleClose();
          // 可以在这里触发刷新列表的事件
          emits("refresh-list"); // 需要先在 defineEmits 中定义
        } else {
          // 图片上传失败，但商品已创建，可以提示用户稍后编辑商品重新上传图片
          ElMessage.warning(
            "商品已添加，但图片上传失败，请稍后在编辑页面重新上传"
          );
          handleClose();
        }
      } catch (error) {
        ElMessage.warning(
          "商品已添加，但图片上传失败，请稍后在编辑页面重新上传"
        );
        handleClose();
      }
    } else {
      ElMessage.error(response.data.msg || "添加失败");
    }
  } catch (error) {
    ElMessage.error(error.message || "添加商品失败，请稍后重试");
  }
};

// 图片上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("上传��像图片只能是 JPG/PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};

const imageUrl = ref("");

// 添加加载数据的方法
const loadData = async () => {
  try {
    // 加载商品类型数据
    const typeResponse = await axios.get("/good_types", {
      headers: {
        Authorization: sessionStorage.getItem("Authorization"),
      },
    });
    if (typeResponse.data.status === 200) {
      goodTypes.value = typeResponse.data.data;
    }

    // 如果需要加载其他初始数据，可以在这里继续添加
  } catch (error) {
    ElMessage.error("加载数据失败，请稍后重试");
  }
};

// 存储商品类型数据
const goodTypes = ref([]);

// 修改 el-select 的选项部分
const typeOptions = computed(() => {
  return goodTypes.value.map((type) => ({
    label: type.typeName,
    value: type.typeId,
  }));
});

// 如果希望组件挂载时就加载数据，可以添加
onMounted(() => {
  loadData();
});

defineExpose({
  dialogVisible,
});
</script>